package DFS;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution90 {


    public static void main(String[] args) {
        int[] nums = new int[]{4,4,4,1,4};

        System.out.println(subsetsWithDup(nums));
    }

    public static List<List<Integer>> subsetsWithDup(int[] nums) {
        List<Integer> chain = new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        boolean[] pb = new boolean[nums.length];
        Arrays.sort(nums);
        dfs(nums, 0, pb, chain, res);
        return res;
    }


    public static void dfs(int[] nums, int index, boolean[] pb, List<Integer> chain, List<List<Integer>> res) {
        res.add(new ArrayList<>(chain));
        if (index >= nums.length) {
            return;
        }
        for (int i = index; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && !pb[i - 1]) {
                continue;
            }
            chain.add(nums[i]);
            pb[i] = true;
            dfs(nums, i + 1, pb, chain, res);
            chain.remove(chain.size() - 1);
            pb[i] = false;
        }
    }
}
